package com.ykq.filter;

import com.alibaba.fastjson.JSON;
import com.ykq.MsgResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    //核心代码 --- 黑白名单
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径的token值
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        ServerHttpResponse response = exchange.getResponse();
        if("admin".equals(token)){
            return chain.filter(exchange);//放行
        }
        try {
            MsgResult data = new MsgResult();
            data.setCode(401);
            data.setMessage("非法请求");
            //byte[] datas = JsonUtils.toJson(data).getBytes(StandardCharsets.UTF_8);
            byte[] datas = JSON.toJSONString(data).getBytes("utf-8");
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }catch (Exception e){
            throw new RuntimeException("");
        }
    }

    //得到过滤器的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
